import query from '@dfeidao/atom-nodejs/db/query';
import format from '@dfeidao/atom-nodejs/dt/format';
import log from '@dfeidao/atom-nodejs/logger/log';
import { systemid } from '../atom/config';


import { IncomingHttpHeaders } from 'http';

interface Message {
	sort: { docdate: 1 | -1 };
	page_size: number;
	name: string;
	page_no: number;
	asc: string[];
	desc: string[];
}

interface IA {
	doccode: string;
	docdate: number;
	Date?: string;
}

interface IWebResult {
	data: unknown;
	cookie?: {
		[name: string]: string;
	} | null;
	content_type?: string;
	headers?: {
		[key: string]: string;
	};
	attachment?: string;
	redirect?: string;
	status_code?: number;
}

export default async function atom(message: Message, action_id: string, session_id: string, headers: IncomingHttpHeaders): Promise<IWebResult> {
	log('Service begin path:e:\gitee\dfeidao\daoke-wxapp\src\service\s002,action_id:' + action_id);


	const asc: string[] = [];
	const desc: string[] = [];
	if (message.sort) {
		const key = Object.keys(message.sort)[0];
		if (message.sort[key] === -1) {
			desc.push(key);
		} else if (message.sort[key] === 1) {
			asc.push(key);
		}
	}

	const { exec, prepare } = query(action_id, session_id, systemid);
	prepare('buffet_orders', ['_id', 'commodityid', 'commodity_name', 'account_sum', 'docdate', 'doccode', 'docstatus', 'picture'], {}, message.page_size, message.page_no, asc, desc);
	const [data] = await exec<IA>();
	const doccodes = [] as string[];
	data.map((item) => {
		doccodes.push(item.doccode);
		item.Date = format(item.docdate, 'yyyy-mm-dd HH:MM:ss');
	});

	const { exec: e1, prepare: p1 } = query(action_id, session_id, systemid);
	p1('buffet_orders', [
		'doccode',
		'copy_single_way_no'
	], { doccode: { $in: doccodes } }, 200, 1, [], []);
	const [data1] = await e1<{
		doccode: string;
		copy_single_way_no: string;
		payment: string;
	}>();
	data1.forEach((item) => {
		// console.log(item.copy_single_way_no);
		if (item.copy_single_way_no === '01') {
			item.payment = '../../imgs/wx.png';
		} else if (item.copy_single_way_no === '02') {
			item.payment = '../../imgs/zf.png';
		}
	});


	// 合并
	const M2 = data1.reduce((p, c) => {
		const obj = JSON.stringify({
			doccode: c.doccode
		});
		p.set(obj, c.payment);
		return p;
	}, new Map<string, string>());
	const data2 = data.map((i) => {
		const obj = JSON.stringify({
			doccode: i.doccode
		});
		return { ...i, payment: M2.get(obj) };
	});

	log('Service end path:e:\gitee\dfeidao\daoke-wxapp\src\service\s002,action_id:' + action_id);
	return {
		data: data2
	};
}
